package com.lucy.disk.controller;

import com.lucy.common.constant.HttpStatus;
import com.lucy.common.exception.BusinessException;
import com.lucy.disk.domain.entity.FileEntity;
import com.lucy.disk.loader.OfficeServiceLoader;
import com.lucy.disk.loader.StorageServiceLoader;
import com.lucy.disk.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author kindear
 * DISK 提供预览服务
 * 需要安装 onlyoffice
 */
@Controller
@RequestMapping("disk")
@Api(tags = "预览服务")
public class PreviewController {
    @Autowired
    OfficeServiceLoader officeService;

    @Autowired
    FileService fileService;

    @Autowired
    StorageServiceLoader storageService;



    @GetMapping("preview/{documentKey}")
    @ApiOperation(value = "文档预览",notes = "支持office文档和pdf,txt等")
    public ModelAndView viewOffice(@PathVariable(value = "documentKey") String documentKey, HttpServletResponse response) throws IOException {
        // 获取渲染文件信息
        return officeService.loadPreviewView(documentKey,response);
    }

    // 配置方法为隐藏方法，通过文档预览进行重定向
    @ApiIgnore
    @GetMapping("default/preview/{fileId}")
    @ApiOperation(value = "文件预览",notes = "")
    public ResponseEntity<byte[]> previewById(@PathVariable("fileId") String fileId, HttpServletRequest request) throws Exception {
        Optional<FileEntity> fileOp = fileService.getOne(fileId);
        if (!fileOp.isPresent()){
            throw new BusinessException(HttpStatus.NOT_FOUND);
        }
        FileEntity fileEntity = fileOp.get();

        String ossUrl = fileEntity.getOssUrl();

        InputStream stream = storageService.downloadFile(ossUrl);

        return fileService.previewMethod(stream,request,fileEntity);
    }

}
